import React from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { DatePicker, Row, Card, Button, Form, Input, Modal, message, Radio } from 'antd';
import { findDicByCodeSort } from '@/support/common';
import { isSemVer } from 'validator';
import { routerRedux } from 'dva/router';
import PateoUploadImage from '@/components/common/PateoForm/uploadImage/PateoUploadImage';

const layout = {
  width: 400,
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};

const mapStateToProps = (state: any) => ({
  listData: state?.operationTools?.pageData,
  loading: state.loading.effects['operationTools/getFetchPage'],
  dicData: state?.menu?.dicData,
  userProfile: state?.menu?.userProfile,
});
const versionDetail: React.FC = props => {
  const {
    dispatch,
    dicData,
    userProfile,
    location: { state = {} },
  } = props;
  const { formData, isEdit } = state;
  const operator = userProfile.userName;

  const systemTypeOptions = findDicByCodeSort(dicData, 'appSystemType');

  const initialValues = isEdit
    ? {
        ...formData,
        publishTime: moment(formData.publishTime),
      }
    : {
        description: '',
        version: '',
        platform: 1,
        publishTime: '',
        qrcodeImgUrl: '',
      };

  const [form] = Form.useForm();

  const goBack = () => {
    dispatch(routerRedux.push({ pathname: '/operationTools/appVersionControl' }));
  };

  const handleAdd = values => {
    dispatch({
      type: 'operationTools/postObj',
      payload: {
        url: '/mscontent/tools/appversion/add',
        ...values,
        operator,
      },
      callback: res => {
        message.success('新增版本成功');
        goBack();
      },
    });
  };
  const handleUpdate = values => {
    dispatch({
      type: 'operationTools/putObj',
      payload: {
        url: '/mscontent/tools/appversion/edit',
        sid: formData.sid,
        ...values,
      },
      callback: res => {
        message.success('修改版本成功');
        goBack();
      },
    });
  };

  const onFinish = (formData: any) => {
    const values = {
      ...formData,
      publishTime: moment(formData.publishTime).format('YYYY-MM-DD HH:mm'),
    };
    if (isEdit) {
      handleUpdate(values);
    } else {
      handleAdd(values);
    }
  };

  const handleUploadQrCode = (_, url) => {
    form.setFieldValue('qrcodeImgUrl', url);
  };

  return (
    <Card>
      <Form
        {...layout}
        initialValues={initialValues}
        form={form}
        name="control-hooks"
        onFinish={onFinish}
        style={{ width: 600 }}
      >
        <Form.Item name="platform" label="操作系统" rules={[{ required: true }]}>
          <Radio.Group disabled={isEdit}>
            {systemTypeOptions.map(option => (
              <Radio value={parseInt(option.dictKey)}>{option.dictValue}</Radio>
            ))}
          </Radio.Group>
        </Form.Item>
        <Form.Item
          name="version"
          label="版本号"
          extra="请注意新版本号不能低于历史最高版本"
          rules={[
            { required: true },
            {
              validator: (_, text) => {
                if (!text) {
                  return Promise.resolve();
                }
                if (!isSemVer(text)) {
                  return Promise.reject('请输入正确的版本号');
                }
                return Promise.resolve();
              },
            },
          ]}
        >
          <Input placeholder="请输入版本号，例：1.0.0" disabled={isEdit} />
        </Form.Item>
        <Form.Item
          name="description"
          label="版本描述"
          rules={[
            { required: true },
            {
              validator: (_, text) => {
                if (!text) {
                  return Promise.resolve();
                }
                if (text.length > 200 || text.length < 2) {
                  return Promise.reject('版本描述长度需要在2-200字符之间');
                }
                return Promise.resolve();
              },
            },
          ]}
        >
          <Input.TextArea placeholder="请输入更新描述" maxLength={200} showCount />
        </Form.Item>
        <Form.Item
          name="publishTime"
          label="发布时间"
          rules={[{ required: true }]}
          tooltip="蒲公英发布的时间"
        >
          <DatePicker
            placeholder="日历控件，可选择年-月-日 时-分"
            format="YYYY-MM-DD HH:mm"
            showTime={{
              format: 'YYYY-MM-DD HH-mm',
            }}
          />
        </Form.Item>
        <Form.Item name="qrcodeImgUrl" label="安装包链接" rules={[{ required: true }]}>
          <PateoUploadImage
            accept=".jpg,.jpeg,.png"
            text="上传二维码"
            onUploadSuccess={handleUploadQrCode}
            maxCount={1}
            value={isEdit ? initialValues.qrcodeImgUrl : undefined}
          />
          支持上传jpg、png、jpeg格式
        </Form.Item>
        <Form.Item>
          <Row justify="end">
            <Button key="cancel" style={{ marginRight: 12 }} htmlType="button" onClick={goBack}>
              取消
            </Button>
            <Button key="confirm" type="primary" htmlType="submit">
              确定
            </Button>
          </Row>
        </Form.Item>
      </Form>
    </Card>
  );
};

export default connect(mapStateToProps)(versionDetail);
